<template>
  <div class="schedule-management">
    <div class="page-header">
      <h1>排班管理</h1>
      <p>管理医生排班信息</p>
    </div>
    
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="排班日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="科室">
          <el-tree-select 
            v-model="searchForm.departmentId" 
            placeholder="请选择科室"
            clearable
            filterable
            @change="handleSearch"
            :data="departmentTree"
            node-key="id"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children'
            }"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="排班状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态"
            clearable
            filterable
            @change="handleSearch"
          >
            <el-option label="正常" :value="1" />
            <el-option label="停诊" :value="0" />
            <el-option label="满号" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card shadow="never" v-if="isAdmin">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增排班
          </el-button>
          <el-button type="success" @click="showBatchAddDialog">
            <el-icon><DocumentAdd /></el-icon>
            批量排班
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-statistic 
            title="排班总数" 
            :value="statistics.totalSchedules || 0"
            :value-style="{ color: '#409EFF' }"
          />
        </div>
      </div>
    </el-card>

    <!-- 排班列表 -->
    <el-card shadow="never">
      <el-table 
        :data="scheduleList" 
        v-loading="loading"
        border
        stripe
      >
        <el-table-column label="排班日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.scheduleDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="doctorName" label="医生姓名" width="100" />
        <el-table-column prop="departmentName" label="科室" width="120" />
        <el-table-column label="时段" width="80">
          <template #default="{ row }">
            <el-tag :type="getTimeSlotTagType(row.timeSlot)">
              {{ getTimeSlotName(row.timeSlot) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.startTime) }} - {{ formatTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="挂号费" width="100">
          <template #default="{ row }">
            <span class="registration-fee">¥{{ formatFee(row.registrationFee) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预约情况" width="120">
          <template #default="{ row }">
            <span>{{ row.bookedCount }}/{{ row.availableCount }}</span>
            <el-progress 
              :percentage="getBookingPercentage(row)" 
              :stroke-width="4"
              :show-text="false"
              style="margin-top: 4px;"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" v-if="isAdmin" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
              :disabled="row.status === 2"
            >
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleStatusChange(row, command)">
              <el-button type="warning" size="small">
                状态 <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1" :disabled="row.status === 1">设为正常</el-dropdown-item>
                  <el-dropdown-item command="0" :disabled="row.status === 0">设为停诊</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              :disabled="row.bookedCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  DocumentAdd, 
  ArrowDown 
} from '@element-plus/icons-vue'
import { 
  getScheduleList,
  updateScheduleStatus,
  deleteSchedule,
  getScheduleStatistics
} from '@/api/business'
import { getDepartmentTree } from '@/api/business'
import { addDialog } from '@/components/gDialog/index'
import ScheduleHandle from '@/views/adminModal/scheduleHandle.vue'
import BatchScheduleHandle from '@/views/adminModal/batchScheduleHandle.vue'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const isAdmin = computed(() => userStore.isAdmin)
// 响应式数据
const loading = ref(false)
const departmentTree = ref([])
const scheduleList = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  departmentId: null,
  status: null
})

// 统计数据
const statistics = ref({})

// 工具方法
const getTimeSlotName = (timeSlot) => {
  const map = { 1: '上午', 2: '下午', 3: '晚上' }
  return map[timeSlot] || '未知'
}

const getTimeSlotTagType = (timeSlot) => {
  const map = { 1: 'success', 2: 'warning', 3: 'info' }
  return map[timeSlot] || ''
}

const getStatusName = (status) => {
  const map = { 0: '停诊', 1: '正常', 2: '满号' }
  return map[status] || '未知'
}

const getStatusTagType = (status) => {
  const map = { 0: 'danger', 1: 'success', 2: 'warning' }
  return map[status] || ''
}

const getBookingPercentage = (row) => {
  if (row.availableCount === 0) return 0
  return Math.round((row.bookedCount / row.availableCount) * 100)
}

const formatDate = (date) => {
  if (!date) return ''
  // 如果已经是字符串格式，直接返回
  if (typeof date === 'string') {
    // 处理YYYY-MM-DD格式
    if (date.includes('-')) {
      return date
    }
  }
  // 处理Date对象
  if (date instanceof Date) {
    return date.toISOString().split('T')[0]
  }
  return date.toString()
}

const formatTime = (time) => {
  if (!time) return ''
  // 如果已经是HH:MM格式，直接返回
  if (typeof time === 'string' && time.includes(':')) {
    return time.substring(0, 5) // 只显示HH:MM，去掉秒数
  }
  return time.toString()
}

// 格式化金额
const formatFee = (fee) => {
  if (!fee) return '0.00'
  return Number(fee).toFixed(2)
}

// 获取科室树形数据
const getDepartmentTreeData = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
  }
}

// 获取排班列表
const fetchScheduleList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      departmentId: searchForm.departmentId,
      status: searchForm.status,
      startDate: searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : null,
      endDate: searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : null,
    }
    

    const response = await getScheduleList(params)
    if (response.code === 200) {
      // 适配新的分页数据结构
      if (response.data && response.data.list) {
        scheduleList.value = response.data.list || []
        total.value = response.data.total || 0
      } else {
        // 兼容旧格式（以防万一）
        scheduleList.value = response.data || []
        total.value = response.total || 0
      }
    }
  } catch (error) {
    console.error('获取排班列表失败:', error)
    ElMessage.error('获取排班列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const params = {}
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    const response = await getScheduleStatistics(params)
    if (response.code === 200) {
      statistics.value = response.data || {}
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 事件处理
const handleSearch = () => {
  currentPage.value = 1
  fetchScheduleList()
  fetchStatistics()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    dateRange: [],
    departmentId: null,
    status: null
  })
  handleSearch()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  fetchScheduleList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchScheduleList()
}

const showAddDialog = () => {
  addDialog({
    title: '新增排班',
    component: ScheduleHandle,
    width: '600px',
    props: {
      scheduleData: {},
      isEdit: false
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchScheduleList()
        fetchStatistics()
      }
    }
  })
}

const showBatchAddDialog = () => {
  addDialog({
    title: '批量排班',
    component: BatchScheduleHandle,
    width: '800px',
    props: {},
    callBack: (result) => {
      if (result === 'success') {
        fetchScheduleList()
        fetchStatistics()
      }
    }
  })
}

const handleEdit = (row) => {
  addDialog({
    title: '编辑排班',
    component: ScheduleHandle,
    width: '600px',
    props: {
      scheduleData: row,
      isEdit: true
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchScheduleList()
        fetchStatistics()
      }
    }
  })
}

const handleStatusChange = async (row, status) => {
  try {
    const response = await updateScheduleStatus(row.id, parseInt(status), '')
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
      fetchScheduleList()
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个排班吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteSchedule(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchScheduleList()
      fetchStatistics()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 生命周期
onMounted(() => {
  getDepartmentTreeData()
  handleSearch()
})
</script>

<style scoped>
.schedule-management {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.registration-fee {
  color: #f56c6c;
  font-weight: 500;
}
</style> 